using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.Security;
using Castle.MonoRail.Framework;
using Castle.MonoRail.Framework.Helpers;
using Saffron.Framework.Users;
using DogBite.Dachshund.Configuration;

namespace Saffron.Filters
{
    public class NavigationFilter : IFilter
    {
        #region IFilter Members

        public bool Perform(ExecuteEnum exec, IRailsEngineContext context, Controller controller)
        {
            
            UserAccount user = (UserAccount)context.Session["user"];
            List<Navigation> navs = GetNavigations(user);

            controller.PropertyBag.Add("navs", navs.ToArray());

            // Everything is ok
            return true;
        }

        internal List<Navigation> GetNavigations(UserAccount user)
        {
            if (user == null)
                return DefaultNavigation();

            

            List<Navigation> userNavigation = new List<Navigation>();

            userNavigation.Add(new Navigation("User.Index", "Home", "/useraccount/Index.rails"));
            userNavigation.Add(new Navigation("User.Edit", "Edit Profile", "/useraccount/Edit.rails"));
                
            if (user.IsInRole(SystemRoleType.User.ToString()))
            {
                //Build user navigation
                userNavigation.Add(new Navigation("Project.Find", "Projects", "/project/Index.rails"));
                
            }

            if (user.IsInRole(SystemRoleType.Admin.ToString()))
            {
                userNavigation.Add(new Navigation("Admin.Users", "Admin Users", "/admin/Users.rails"));
                userNavigation.Add(new Navigation("Admin.System", "Admin System Data", "/admin/SystemData.rails"));
            }

            userNavigation.Add(new Navigation("Login.Signout", "Signout", "/Login/Signout.rails"));
            return userNavigation;
        }

        private List<Navigation> DefaultNavigation()
        {
            
            List<Navigation> defaultNav = new List<Navigation>();
            defaultNav.Add(new Navigation("Home.Index", "Home", "/home/Index.rails"));
            defaultNav.Add(new Navigation("Home.About", "About", "/home/About.rails"));
            defaultNav.Add(new Navigation("Login.Index", "Login", "/Login/Index.rails"));

            return defaultNav;
        }

        #endregion
    }
}
